<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <!-- 表格组件：用于展示已有得平台数据 -->
      <!-- table:---border:可以设置表格纵向是否有边框
                table-column:---label:某一个列表 ---width:设置这列宽度 ---align:设置这一列对齐方式    
            -->
      <el-table style="margin: 10px 0px" border :data="trademarkArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <!-- table-column:默认展示数据用div -->
        <el-table-column label="品牌名称" prop="tmName"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}?`"
              width="250px"
              icon="Delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="sizeChange"
        @current-change="getHasTrademark"
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
    <!-- 
            v-model:属性用户控制对话框的显示与隐藏的 true显示 false隐藏
             title:设置对话框左上角标题
        -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="handleAvatarSuccess"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="cancel(formRef)"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="submitForm(formRef)"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormRules, FormInstance } from "element-plus";
import {
  getProductlist,
  delProductOnes,
  uplodaImg,
  addProduct,
  changProduct,
} from "@/api/product";
import {
  Records,
  ResponseData,
  TradeMark,
  TradeMarkResponseData,
} from "@/api/product/type";

// 模态框
const dialogFormVisible = ref<boolean>(false);
// 模态框所需from数据
const trademarkParams = reactive<TradeMark>({
  id: "",
  tmName: "",
  logoUrl: "",
});
// 当前页码
const pageNo = ref<number>(1);
// 每页多少条
const limit = ref<number>(3);
// 总共条数
const total = ref<number>(0);
// 列表数据
const trademarkArr = ref<Records>([]);
// 当页一页条数
const sizeChange = (e: number) => {
  limit.value = e;
  getTrademarkArr(1);
};
// 页码改变
const getHasTrademark = (e: number) => {
  getTrademarkArr(e);
};

// 获取列表数据
const getTrademarkArr = async (page: number) => {
  pageNo.value = page;
  const result: TradeMarkResponseData = await getProductlist(
    pageNo.value,
    limit.value
  );
  if (result.code == 200) {
    //存储已有品牌总个数
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};
// 添加商品按钮弹窗
const addTrademark = () => {
  dialogFormVisible.value = !dialogFormVisible.value;
};

// 修改
const updateTrademark = (row: any) => {
  Object.assign(trademarkParams, {
    id: row.id,
    tmName: row.tmName,
    logoUrl: row.logoUrl,
  });
  dialogFormVisible.value = !dialogFormVisible.value;
};
// 删除
const removeTradeMark = async (id: number) => {
  const result = await delProductOnes(id);
  if (result.code == 200) {
    //删除成功提示信息
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    //再次获取已有的品牌数据
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1
    );
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
// 图片上传
const handleAvatarSuccess = async (e: any) => {
  // 定义结构参数的类型
  interface fileType {
    size: number;
    type: string;
  }
  const { size, type }: fileType = e.file;
  if (istrue(size, type)) {
    let params: any = new FormData();
    params.append("file", e.file);
    const result: ResponseData = await uplodaImg(params);
    if (result.code == 200) {
      trademarkParams.logoUrl = result.data;
      ElMessage({
        type: "success",
        message: result.message,
      });
    }
  }
};
// 上传验证
const istrue = (size: number, type: string): boolean => {
  if (
    type == "image/png" ||
    type == "image/jpeg" ||
    type == "image/jpg" ||
    type == "image/gif"
  ) {
    if (size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件格式务必PNG|JPG|GIF",
    });
    return false;
  }
};
// form ref
const formRef = ref<FormInstance>();
// rules规则
const rules = reactive<FormRules>({
  tmName: [{ required: true, message: "输入品牌名称", trigger: "blur" }],
  logoUrl: [{ required: true, message: "上传商品图片", trigger: "chang" }],
});
// 确认新增
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: any, fields: any) => {
    if (valid) {
      const result = trademarkParams.id
        ? await changProduct(trademarkParams)
        : await addProduct(trademarkParams);
      if (result.code == 200) {
        ElMessage({
          type: "success",
          message: result.message,
        });
      } else {
        ElMessage({
          type: "error",
          message: "操作失败",
        });
      }
      addTrademark(); //关闭模态框
      Object.assign(trademarkParams, { id: "", tmName: "", logoUrl: "" });
    } else {
      ElMessage({
        type: "error",
        message: "请填写完成内容",
      });
    }
  });
};
const cancel = () => {
  dialogFormVisible.value = false;
  Object.assign(trademarkParams, { id: "", tmName: "", logoUrl: "" });
};
onMounted(() => {
  getTrademarkArr(1);
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
